<template>
  <div class="app-container">
    <!--面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>
    <br>

    <!--模糊查询模块-->
    <el-form :model="queryParams" inline>
      <el-form-item label="部门名称" prop="deptName" :inline="true">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          style="width: 200px"
          @clear=""
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable size="small">
          <el-option
            v-for="dict in deptDict"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery()">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="ruleForm">重置</el-button>
      </el-form-item>
    </el-form>
    <!--添加按钮模块-->
    <el-form v-show="Search" inline>
      <el-form-item>
        <el-col>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handelAdd">新增
          </el-button>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-sort"
            size="mini"
            @click="toggleExpandAll"
          >展开/折叠
          </el-button>
        </el-col>
      </el-form-item>
    </el-form>
    <!--数据展示-->
    <el-table
      v-if="refreshTable"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :header-cell-style="{'text-align':'left '}"
      :cell-style="{'text-align':'left'}"
      :tree-props="{children: 'deptMenus'}">
      <el-table-column prop="deptName" label="部门名称" width="300"/>
      <el-table-column prop="orderNum" label="排序" width="300"/>
      <el-table-column label="状态" align="center" width="300">
        <template slot-scope="scope">
          <el-switch
            v-if="scope.row.deptId===100?false:true"
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="400"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handelAdd(scope.row)"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handelDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--添加/修改 form表单-->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col v-if="form.parentId !== 0" :span="24">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="form.parentId"
                          :options="deptMenus"
                          :normalizer="normalizer"
                          :show-count="true"
                          placeholder="请选择上级部门"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio v-model="form.status"
                  v-for="dict in deptDict"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}
              </el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

    import Treeselect from '@riophae/vue-treeselect'
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'

    export default {
        name: 'Dept',
        components: {Treeselect},
        data() {
            return {
                // 模糊查询参数
                queryParams: {
                    deptName: '',
                    status: ''
                },
                // 是否展开，默认全部展开
                isExpandAll: true,
                // 重新渲染表格状态
                refreshTable: true,
                // 是否显示
                Search: true,
                treeProps: {
                    label: 'deptName',
                    children: 'deptMenus'
                },
                // 部门下拉选择
                deptMenus: [],
                // 部门数据集合
                deptList: [],
                // 是否显示 添加/修改 弹出窗口
                open: false,
                // 弹出层标题
                title: '',
                // 部门状态
                deptDicts: ['sys_normal_disable'],
                //
                deptDict: {
                    sys_normal_disable: '',
                    dictValue: '',
                    dictLabel: ''
                },
                // 表单参数
                form: [],
                // 表单校验
                rules: {
                    parentId: [
                        {required: true, message: '上级部门不能为空', trigger: 'blur'}
                    ],
                    deptName: [
                        {required: true, message: '部门名称不能为空', trigger: 'blur'}
                    ],
                    orderNum: [
                        {required: true, message: '显示排序不能为空', trigger: 'blur'}
                    ],
                    email: [
                        {
                            type: 'email',
                            message: "'请输入正确的邮箱地址",
                            trigger: ['blur', 'change']
                        }
                    ],
                    phone: [
                        {
                            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                            message: '请输入正确的手机号码',
                            trigger: 'blur'
                        }
                    ]
                }
            }
        },
        // 钩子函数
        created() {
            this.getDept()
        },
        methods: {
            // 获取部门列表数据
            getDept: function () {
                this.axios.get('/dept').then(res => {
                    this.deptList = res.data
                    this.deptMenus = res.data;
                    console.log(res.data)
                })
                console.log(this.deptDicts)
                this.axios.get('/dict/maps/' + this.deptDicts.join()).then(res => {
                    this.deptDict = res.data.sys_normal_disable['dictData']
                })
            },
            // 模糊查询重置按钮
            ruleForm() {
                this.queryParams = {
                    deptName: '',
                    status: ''
                }
                this.getDept()
            },
            // 模糊查询搜索
            handleQuery() {
                this.axios.get('/queryPage?deptName=' + this.queryParams.deptName + '&status=' + this.queryParams.status).then(res => {
                    console.log(res)
                    this.deptList = res.data
                })
            },
            // 状态修改
            handleStatusChange(row) {
                console.log('上表')
                this.form = row
                const strings = row.ancestors.split(',')
                console.log(strings)
                const length = strings.length
                console.log(length)
                if (length === 1) {
                    this.form.parentId = 0
                } else if (length === 2) {
                    this.form.parentId = strings[1]
                } else {
                    this.form.parentId = strings[2]
                }
                this.form = {
                    deptId: row.deptId,
                    parentId: row.parentId,
                    deptName: row.deptName,
                    orderNum: row.orderNum,
                    leader: row.leader,
                    phone: row.phone,
                    email: row.email,
                    status: row.status
                }
                this.axios.put('/update', this.form).then(res => {
                    if (res.data === "no") {
                        this.$message.error('状态修改失败！' + this.form.deptName + "下存在人员")
                        this.getDept()
                    } else if (res.data === "ok") {
                        this.$message.success('修改成功！')
                        this.open = false
                        this.getDept()
                    } else {
                        this.$message.error('状态修改失败！' + this.form.deptName + "下存在正常部门")
                        this.getDept()
                    }
                })
                this.axios.get('/dict/maps/' + this.deptDicts.join()).then(res => {
                    this.deptDict = res.data.sys_normal_disable['dictData']
                    console.log('-----------------------------')
                    console.log(res)
                    // console.log(this.deptDict)
                })
            },
            // 重置表单
            reset() {
                this.form = {
                    deptId: '',
                    parentId: undefined,
                    deptName: '',
                    orderNum: '',
                    leader: '',
                    phone: '',
                    email: '',
                    status: '0'
                }
            },
            // 修改按钮
            handleUpdate(row) {
                console.log(row)
                if (row.status !== '0') {
                    this.$message.error('该部门被停用，无法修改！')
                } else {
                    const strings = row.ancestors.split(',')
                    const length = strings.length
                    if (length === 1) {
                        row.parentId = 0
                    } else if (length === 2) {
                        row.parentId = 0
                    } else {
                        row.parentId = strings[2]
                    }
                    this.form = {
                        deptId: row.deptId,
                        parentId: row.parentId,
                        deptName: row.deptName,
                        orderNum: row.orderNum,
                        leader: row.leader,
                        phone: row.phone,
                        email: row.email,
                        status: row.status
                    }
                    this.open = true
                    this.title = '修改部门'
                }
            },
            // 表单确定按钮
            submitForm() {
                console.log('下表')
                console.log(this.form)
                if (this.form.parentId === '' || this.form.parentId === undefined) {
                    this.form.parentId = 100
                }
                if (this.form.deptId !== '') {
                    if (this.form.status === '正常') {
                        this.form.status = '0'
                    }
                    // console.log(this.form)
                    this.axios.put('/update', this.form).then(res => {
                        if (res.data !== 'ok') {
                            this.$message.error('修改失败，该部门下存在人员')
                            this.open = false
                            this.getDept()
                        } else {
                            this.$message.success('修改成功！')
                            this.open = false
                            this.getDept()
                        }
                    })
                } else {
                    if (this.form.status === '正常') {
                        this.form.status = '0'
                    }
                    if (this.form.parentId === '' || this.form.deptName === '' || this.form.leader === '' || this.form.email === ''
                        || this.form.orderNum === '' || this.form.phone === '') {
                        this.$message.info("信息未全部填写完成，提交失败！")
                    } else {
                        this.axios.post('/add', this.form).then(res => {
                            if (res.data !== 'ok') {
                                this.$message.error('添加失败')
                            } else {
                                this.$message.success('添加成功')
                                this.getDept()
                            }
                        })
                        this.open = false
                    }
                }
            },
            // 添加/修改表单 取消按钮
            cancel() {
                this.open = false
                this.reset()
                this.getDept()
            },
            //树的展开与折叠
            toggleExpandAll() {
                this.refreshTable = false
                this.isExpandAll = !this.isExpandAll
                this.$nextTick(() => {
                    this.refreshTable = true
                })
            },
            // 添加按钮操作
            handelAdd(row) {
                // 显示窗口和标头
                console.log(row)
                // 新增赋值，默认‘0’
                if (row.ancestors === undefined) {
                    row.ancestors = '0'
                    row.status = '0'
                }
                if (row.status !== '0') {
                    this.$message.error('部门被停用，无法操作哦!')
                } else {
                    // 获取ancestors中的id数量
                    const num = row.ancestors.split(',').length - 1
                    console.log(num)
                    if (num > 1) {
                        this.$message.error('抱歉，目前最多只能添加到部门哦！')
                    } else {
                        this.reset()
                        this.getDept()
                        if (num === 1) {
                            this.form.parentId = row.deptId
                        } else {
                            this.form.parentId = undefined
                        }
                        this.open = true
                        this.title = '添加部门'
                    }
                }
            },
            // 删除操作
            handelDelete(row) {
                const lb = this
                // console.log(row.deptId)
                if (this.$confirm('是否删除此为' + row.deptName + '的数据？', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async function () {
                    const {data: res} = await lb.axios.delete('delete/' + row.deptId);
                    console.log(res)
                    if (res === 'ok') {
                        lb.$message.success('删除成功！')
                        lb.getDept()
                    } else if (res === "no") {
                        lb.$message.error('删除失败了！，' + row.deptName + "下存在用户哦")
                        lb.getDept()
                    } else {
                        lb.$message.error('删除失败了！，' + row.deptName + "下存在部门哦")
                        lb.getDept()
                    }
                })) {
                }
            },
            // 转换部门数据结构
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children
                }
                if (node.deptName === null) {
                    node.deptName = '智慧社区'
                }
                return {
                    id: node.deptId,
                    label: node.deptName,
                    children: node.deptMenus,
                    isDisabled: node.parentId ===0 || node.parentId === 100 ? false : true
                }
            }
        }
    }
</script>

<style>

</style>

